package com.closer.service.biz.user.validator;


import cn.hutool.core.util.StrUtil;
import com.closer.service.repository.UserMapper;
import com.closer.service.support.exception.BusinessException;
import com.closer.service.support.exception.ErrorCode;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.stereotype.Component;

@Component
public class UserValidator {

    private final UserMapper mapper;

    public UserValidator(UserMapper mapper) {
        this.mapper = mapper;
    }

    public void validateRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 基础校验
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        // 2. 检查是否重复
        var queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount", userAccount);
        var count = mapper.selectCountByQuery(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
    }

    public void validateLogin(String userAccount, String userPassword) {
        // 1. 基础校验
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
    }
}
